package com.test;

/*
public class Example02 {
    public static void main(String[] args) {
        int result = divide(4, 0);  //调用divide()方法,第二个参数是0
        System.out.println(result);
    }

    //实现两个整数相除
    public static int divide(int x, int y) {
        return x / y;
    }
}

 */

/*
public class Example02 {
    public static void main(String[] args){
        try {
            int result =divide(4,0);
            System.out.println(result);
        }catch (Exception e){
            System.out.println("捕获的异常信息为:"+e.getMessage());
        }
        System.out.println("程序继续向下执行...");
    }
    public  static int divide(int x, int y){
        return x/y;
    }
}

 */

/*
public class Example02 {
    public static void main(String[] args) {
        try {
            int result = divide(4, 0);
        } catch (Exception e) {
            System.out.println("捕获的异常信息是:" + e.getMessage());
            return;        //用于结束当前语句
        }finally {
            System.out.println("进入finally代码块");
        }
        System.out.println("程序继续向下...");

    }

    public static int divide(int x, int y) {
        return x / y;
    }
}


 */

/*
public class Example02 {
    public static void main(String[] args) {
        try {
            int result = divide(4, 0);
            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();    //打印捕获异常信息
        }

    }

    public static int divide(int x, int y) throws Exception {
        return x / y;
    }
}

 */

/*
public class Example02 {
    public static void main(String[] args) {
        int age = -1;
//        int age = 1;
        try {
            printAge(age);
        } catch (Exception e) {
            System.out.println("捕获的异常信息为:" + e.getMessage());
        }
    }

    public static void printAge(int age) throws Exception {
        if (age <= 0) {
            throw new Exception("输入年龄有误,年龄需是正整数");
        } else {
            System.out.println("年龄为:" + age+"岁");
        }
    }
}

 */
class DivideByMinusException extends Exception {
    public DivideByMinusException(){
        super();
    }
    public DivideByMinusException(String message){
        super(message);
    }
}

public class Example02 {
    public static void main(String[] args){
        //在main()方法中定义try...catch语句用于捕获异常
        try{
            int result =divide(4,-1);
            //Unhandled exception: com.test.DivideByMinusException
            System.out.println(result);
        }catch(DivideByMinusException e){       //对捕获到的异常进行处理
            System.out.println(e.getMessage());     //打印捕获的异常信息
        }


    }

    public static int divide(int x, int y) throws DivideByMinusException{  //Unhandled exception: com.test.DivideByMinusException,使用throws关键字声明抛出自定义异常

        if(y<0){
            throw new DivideByMinusException("除数是负数");
        }
        return x/y;
    }
}